package logic

import (
	"context"
	"errors"
	"short-video-dev/mysql"
	"short-video-dev/videorpc/internal/svc"
	"short-video-dev/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectAddLogic {
	return &CollectAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CollectAddLogic) CollectAdd(in *videorpc.CollectAddRequest) (*videorpc.CollectAddResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.UserInfo
	err := user.FindUserById(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("用户不存在,请先注册")
	}
	var video mysql.VideoInfo
	err = video.VideoFindByOneId(mysql.DB, in.VideoId)
	if err != nil {
		return nil, errors.New("视频不存在")
	}
	var collect mysql.CollectionInfo
	err = collect.FindCollect(mysql.DB, in.UserId, in.VideoId)
	if err != nil {
		return nil, err
	}
	if collect.ID != 0 {
		return nil, errors.New("该视频已收藏")
	}

	collect = mysql.CollectionInfo{
		UserId:  int(in.UserId),
		VideoId: int(in.VideoId),
	}
	err = collect.CollectAdd(mysql.DB, in.VideoId)
	if err != nil {
		return nil, errors.New("添加失败")
	}

	return &videorpc.CollectAddResponse{
		CollectId: int64(collect.ID),
	}, nil
}
